﻿#include "Prop.h"
#include "PropManager.h"
using namespace cocos2d;
using namespace cocos2d::ui;
using namespace cocostudio::timeline;

Prop::Prop(PropType type):
	type(type),
	speed(100),
	blinkCount(0),
	live(true)
{

}

Prop* Prop::create(PropType type) {
	Prop* ret = new (std::nothrow) Prop(type);
	if (ret && ret->init()) {
		ret->autorelease();
		return ret;
	}
	CC_SAFE_DELETE(ret);
	return nullptr;
}

bool Prop::init() {
	if (!Widget::init()) {
		return false;
	}
	size = Director::getInstance()->getVisibleSize();
	initSpriteFrameCache();
	initCSBFile();
	scheduleUpdate();
	schedule(schedule_selector(Prop::blinkUpdate), 1, -1, 10);
	return true;
}

/*
	加载csb文件
*/
void Prop::initCSBFile() {
	root = CSLoader::createNode("scenes/game/ui/prop.csb");
	this->addChild(root);
	propSp = dynamic_cast<Sprite*>(root->getChildByName("prop"));
	propSize = propSp->getContentSize();
	//propPos = convertToWorldSpace(propSp->getPosition());
	//根据类型加载道具
	char filename[30];
	sprintf_s(filename, "prop_ani_%d.png", type);
	propSp->setSpriteFrame(gameSpriteCache->getSpriteFrameByName(filename));

	Node* aniNode;
	if (type < 7) {
		sprintf_s(filename, "scenes/game/ui/prop_ani_1.csb");
	} else {
		sprintf_s(filename, "scenes/game/ui/prop_ani_2.csb");
	}
	aniNode = CSLoader::createNode(filename);
	root->addChild(aniNode);
	aniNode->setPosition(Vec2::ZERO);
	ActionTimeline* propAct = CSLoader::createTimeline(filename);
	propAct->play("run", true);
	aniNode->runAction(propAct);
}

/*
	加载精灵帧缓存
*/
void Prop::initSpriteFrameCache() {
	gameSpriteCache = SpriteFrameCache::getInstance();
	gameSpriteCache->addSpriteFramesWithFile("scenes/game/image/prop/props_ani.plist",
		Director::getInstance()->getTextureCache()->addImage(
			"scenes/game/image/prop/props_ani.png"));		//向帧缓冲中添加纹理图片
}

/*
	移动
*/
void Prop::update(float dt) {
	if (!live) {
		unscheduleUpdate();
		unschedule(schedule_selector(Prop::blinkUpdate));
		PropManager::getInstance()->collection(this);
		return;
	}

	Vec2 pos = root->getPosition();
	if (pos.y < -propPos.y - propSize.height / 4) {//如果道具从屏幕上消失，则让它回到屏幕的最高处
		pos.y = propSize.height / 4 + propPos.y;
	}
	root->setPosition(pos + Vec2(0, -1) * dt * speed);
}

/*
	十秒后道具闪烁5秒，然后再消失
*/
void Prop::blinkUpdate(float dt) {
	Blink* blink2 = Blink::create(1.0f, 3);
	propSp->runAction(blink2);
	blinkCount++;
	if (blinkCount == 5) {
		blinkCount = 0;
		unschedule(schedule_selector(Prop::blinkUpdate));
		live = false;
	}
}

/*
	返回自己的Rect
*/
Rect Prop::getPropRect() {
	float x = convertToWorldSpace(root->getPosition()).x - 50;
	float y = convertToWorldSpace(root->getPosition()).y;
	float width = propSize.width * 0.5;
	float height = propSize.height * 0.5;
	return Rect(x, y, width, height);
}